<?php

namespace app\api\controller;

use app\common\model\BookModel;
use app\common\model\UserFollowBookModel;
use app\common\model\WechatUserModel;
use app\common\service\ElkLog;
use app\common\service\wechat\WeChatCustom;
use app\common\service\wechat\WeChatReceive;
use app\common\service\wechat\WeChatUser;
use think\Controller;
use think\Log;

class Index extends Controller
{
    // 初次关注回复
    const SUBSCRIBE_REPLY = "恭喜注册成功";

    // 取消关注图书
    const USER_ACTION = "delBook";

    /**
     * 用户OPEN_ID
     *
     * @var string
     */
    public $user_open_id = '';

    /**
     * 用户UNION_ID
     *
     * @var string
     */
    public $user_union_id = '';

    /**
     * 用户微信信息数据
     *
     * @var array
     */
    public $user_wx_data = array();

    /**
     * 用户是否已关注公众号
     *
     * @var integer
     */
    public $user_is_subscribe = 0;

    /**
     * 公众号微信号
     *
     * @var string
     */
    public $app_wx_name = '';

    /**
     * 消息类型
     *
     * @var string
     */
    public $msg_type = '';

    /**
     * 事件类型
     *
     * @var string
     */
    public $event = '';

    /**
     * 公众号用户列表ID
     * @var integer
     */
    public $wechat_user_id = 0;

    /**
     * 初始化方法
     */
    protected function initialize()
    {
        $receiveService    = new WeChatReceive();
        $userWeChatService = new WeChatUser();

        $wechatUser        = new WechatUserModel();

        $msgType        = $receiveService->getMsgType();
        $this->msg_type = strtolower($msgType);
        // 事件类型
        $event       = $receiveService->getEvent();
        $this->event = strtolower($event);
        // 用户OpenID
        $this->user_open_id = $receiveService->getOpenid();
        // 当前公众号编号
        $this->app_wx_name = $receiveService->getToOpenid();
        ElkLog::save( array( "message"=> "TestLogin","data" => $this->user_open_id ) );

        // 获取用户信息
        if ($this->user_open_id) {
            $this->user_wx_data = $userWeChatService->getUserInfo($this->user_open_id);
        }

        Log::write( $this->user_wx_data );

        // 初始化用户属性
        if ($this->user_wx_data) {
            $this->user_is_subscribe = (int) $this->user_wx_data['subscribe'];
            $this->user_union_id     = isset($this->user_wx_data['unionid']) ? $this->user_wx_data['unionid'] : '';
            // 初始化关注账户
            $this->wechat_user_id = $wechatUser->initUserData($this->user_wx_data);
        }
    }

    /**
     * 分发消息类型
     */
    public function routeMsgType()
    {
        $receiveService = new WeChatReceive();
        // 区分消息类型
        switch ($this->msg_type) {
            // 事件
            case WeChatReceive::MSGTYPE_EVENT:
                $this->event();
                break;
            // 文本消息
            case WeChatReceive::MSGTYPE_TEXT:
                $this->text();
                break;
            // 其他类型消息处理
            default:
                $content = "错误";
                $receiveService->replyText($content);
                break;
        }
    }

    /**
     * 文本消息处理
     * @todo switch 文本消息方法
     */
    private function text()
    {
        $Book = new BookModel();
        $receiveService    = new WeChatReceive();

        $user_content      = $receiveService->getReceive('Content');

        // 取消关注
        if ( ( strpos($user_content, "取消") !== false ) ) {
            $user_content = str_replace('取消', '', $user_content );
            if ( !$user_content ){
                $receiveService->replyText( "数据错误" );
                return false;
            }
        }

        // 搜索图书
        $data = $Book->where( "title", $user_content )->find();

        // 若搜索到图书则添加到书库
        if ( !$data ){
            $receiveService->replyText( "未搜索到图书,请检查是否输入有误！" );
            return false;
        }

        $data = $data->toArray();

        $add = [
            "user_id" => $this->wechat_user_id,
            "book_id" => $data['id']
        ];

        $UserFollowBook = new UserFollowBookModel();

        $id = $UserFollowBook->insertGetId( $add );

        $receiveService->replyText( "关注成功{$user_content}，稍后将会为您推送最实时的小说更新动态，尽情期待" );
        return true;
    }

    /**
     * 微信事件回调分发处理
     */
    private function event()
    {
        $receiveService    = new WeChatReceive();
        $userWeChatService = new WeChatUser();
        $wechatUser        = new WechatUserModel();
        $wechatCustom      = new WeChatCustom();
        // 区分事件类型
        switch ($this->event) {
            // 订阅 或者 用户未关注时，进行关注后的事件推送
            case WeChatReceive::EVENT_SUBSCRIBE:
                // 文本被动回复
                $content = self::SUBSCRIBE_REPLY;
                $receiveService->replyText($content);
                break;
            // 取消订阅
            case WeChatReceive::EVENT_UNSUBSCRIBE:
                if ($this->user_wx_data) {
                    // 删除关注账户
                    $wechatUser->deleteUserData($this->user_wx_data);
                }
                break;
            // 其它事件默认处理
            default:
                break;
        }
    }

}
